﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using MDT.LifeSewagePlatform.InterfaceService;
using MDT.LifeSewagePlatform.IRepository;
using MDT.LifeSewagePlatform.Entity;
using MDT.LifeSewagePlatform.Conmmon;

namespace MDT.LifeSewagePlatform.Service
{
    public class DrugService : BaseService, IDrugService
    {
        #region 

        [Autowired]
        private IDrugDetailRepository drugDetailRepository { get; set; }
        [Autowired]
        private IDrugRepository drugRepository { get; set; }
        [Autowired]
        private IDetailRepository detailRepository { get; set; }
        [Autowired]
        private IPlaceDutyRepository placeDutyRepository { get; set; }
        [Autowired]
        private ISetAlarmRepository setAlarmRepository { get; set; }
        [Autowired]
        private IAlarmPlaceRepository alarmPlaceRepository { get; set; }
        [Autowired]
        private ISocketHelper sockerHelper { get; set; }
        [Autowired]
        private IConfiguration configuration { get; set; }
        [Autowired]
        private IDrugDayRespository drugDayRepository { get; set; }

        [Autowired]
        private IBuilderWordReportRepository builderWordReportRepository { get; set; }
        [Autowired]
        private ICompanyRepository companyRepository { get; set; }
        [Autowired]
        private ISystemEnvService systemEnvService { get; set; }
        public DrugService()
        {
        }

        #endregion
        public async Task<DataMessage> GetPie(PipeLineParameter Params, CurrentUserInfo currentUserInfo)
        {
            var quarter = Params.Month.GetQuarter();
            int pastquarter = quarter.GetPastQuarter();
            int pastyear = quarter.GetByPastQuarterYear(Params.Year);

            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
            };
            List<PieView> pidViews = new List<PieView>();

            IQueryable<DrugDetailUnion> drugDetaionViews = drugDetailRepository.GetDrugDetails(t => Params.Year == t.MonitorTime.Year);

            drugDetaionViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugDetaionViews);
            drugDetaionViews = await QueryPipeLineTime(pipeLineParameter, drugDetaionViews);
            #region 映射成键值对 等待优化
            if (await drugDetaionViews.AnyAsync())
            {
                var data = await drugDetailRepository.GroupByAverage(drugDetaionViews);
                Type type = typeof(DrugDetailEntity);
                foreach (var item in type.GetProperties())
                {
                    string name = item.GetColName();
                    if (name.Contains("（") && item.PropertyType == typeof(double))
                    {
                        PieView view = new PieView();
                        name = name.Substring(0, name.IndexOf('（'));
                        view.Name = name;
                        double.TryParse(item.GetValue(data).ToString(), out double val);
                        view.Value = val;
                        pidViews.Add(view);

                    }
                }
                #endregion
            }
            return Ok200("查询成功!", pidViews);
        }
        /// <summary>
        /// 统计折算总量折线数据
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public async Task<DataMessage> GetLineByMonth(LineParameter Params, CurrentUserInfo currentUserInfo)
        {
            List<LineMonthView> lineViews = new List<LineMonthView>();

            var drugDetaionViews = drugDetailRepository.GetDrugDetails(t => Params.Year == t.MonitorTime.Year);

            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
            };

            drugDetaionViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugDetaionViews);

            #region 映射成键值对
            if (await drugDetaionViews.AnyAsync())
            {
                var data = await drugDetailRepository.GroupByAverage(drugDetaionViews, (eGroupGetDateType)_systemConfig.QuarterOrMonth);

                foreach (var item in data)
                {
                    lineViews.Add(new LineMonthView()
                    {
                        Month = item.Key,
                        Value = Math.Round(item.Value, 2)
                    });
                }
            }
            #endregion
            return Ok200("查询成功!", lineViews);
        }

        public async Task<DataMessage> GetLineByYear(LineParameter Params, CurrentUserInfo currentUserInfo)
        {
            List<LineYearView> lineViews = new List<LineYearView>();
            var drugDetaionViews = drugDetailRepository.GetDrugDetails(d => true);

            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
            };
            drugDetaionViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugDetaionViews);


            #region 映射成键值对
            if (await drugDetaionViews.AnyAsync())
            {
                var data = await drugDetailRepository.GroupByAverage(drugDetaionViews, eGroupGetDateType.Year);

                foreach (var item in data)
                {
                    lineViews.Add(new LineYearView()
                    {
                        Year = item.Key,
                        Value = Math.Round(item.Value, 2)
                    });
                }
            }

            #endregion

            return Ok200("查询成功", lineViews);
        }

        public async Task<DataMessage> GetLineByDrugMonth(LineParameter Params, CurrentUserInfo currentUserInfo)
        {
            var drugDetaionViews = drugDetailRepository.GetDrugDetails(t => Params.Year == t.MonitorTime.Year);

            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
            };

            drugDetaionViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugDetaionViews);

            List<LineDrugView> lineViews = new List<LineDrugView>();
            if (await drugDetaionViews.AnyAsync())
            {
                #region 映射键值对

                var data = await drugDetailRepository.GroupByDrugDetailAverage(drugDetaionViews, (eGroupGetDateType)_systemConfig.QuarterOrMonth);

                Type type = typeof(DrugDetailEntity);
                foreach (PropertyInfo prop in type.GetProperties())
                {
                    LineDrugView line = new LineDrugView();
                    List<PieView> pieVew = new List<PieView>();
                    string name = prop.GetColName();
                    if (name.Contains('（') && prop.PropertyType == typeof(double))
                    {
                        foreach (var item in data)
                        {
                            pieVew.Add(new PieView()
                            {
                                Name = item.ID.ToString(),
                                Value = Math.Round((double)prop.GetValue(item), 2)
                            });
                        }
                        lineViews.Add(new LineDrugView()
                        {
                            Lines = pieVew,
                            Name = name.Substring(0, name.IndexOf('（'))
                        });
                    }
                }
                #endregion
            }

            return Ok200("查询成功!", lineViews);
        }

        public async Task<DataMessage> GetLineByDrugYear(LineParameter Params, CurrentUserInfo currentUserInfo)
        {
            List<LineDrugYearView> lineViews = new List<LineDrugYearView>();

            var drugDetaionViews = drugDetailRepository.GetDrugDetails(t =>true);

            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
            };

            drugDetaionViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugDetaionViews);

            #region 映射成键值对数据
            if (await drugDetaionViews.AnyAsync())
            {
                var data = await drugDetailRepository.GroupByDrugDetailAverage(drugDetaionViews, eGroupGetDateType.Year);

                Type type = typeof(DrugDetailEntity);

                foreach (PropertyInfo prop in type.GetProperties())
                {
                    LineDrugYearView line = new LineDrugYearView();
                    List<PieView> pieVew = new List<PieView>();
                    string name = prop.GetColName();
                    if (name.Contains('（') && prop.PropertyType == typeof(double))
                    {
                        foreach (var item in data)
                        {

                            pieVew.Add(new PieView()
                            {
                                Name = item.ID.ToString(),
                                Value = Math.Round((double)prop.GetValue(item), 2)
                            });
                        }

                        line.Name = name.Substring(0, name.IndexOf('（'));
                        line.Lines = pieVew;
                        lineViews.Add(line);
                    }
                }
            }


            #endregion

            return Ok200("查询成功!", lineViews);
        }


        /// <summary>
        /// 查询右下角的图表
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public async Task<BaseMessage> GetDrugs(DrugParameter Params, CurrentUserInfo currentUserInfo)
        {
            #region 基础查询语句
            IQueryable<DrugUnion> drugViews = drugRepository.GetDrugDto(drug => true);
            #endregion


            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
                Year = Params.Year,
            };

            drugViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugViews);
            drugViews = await QueryPipeLineTime(pipeLineParameter, drugViews);

            var data = drugRepository.GroupByDrug(drugViews);

            return Ok200("查询成功!", await PageList<DrugView>.CreateAsync(data, Params));

        }

        public async Task<BaseMessage> GetDrugDetals(DrugParameter Params, CurrentUserInfo currentUserInfo)
        {
            #region 基础查询语句
            IQueryable<DrugDetailUnion> drugViews = drugDetailRepository.GetDrugDetails(drug => true);
            #endregion


            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
                Year = Params.Year,
            };
            var d0 = drugViews.ToArray();
            //drugViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugViews);

            #region 如果是管理员可以看跨地区的数据
            if (Admin(currentUserInfo.RoleName) == false)
            {
                drugViews = drugViews.Where(d => d.CompanyID == currentUserInfo.CompanyID);
            }
            else
            {
                drugViews = drugViews.Where(d => d.CompanyID == Params.CompanyID);
            }
            #endregion


            #region 地区权限只能看自己区域的
            if (Auth(currentUserInfo.PlaceTypeName, Params.AreaID) == false)
            {
                throw new Exception("runtime:你只有地区的权限无法看市区的数据请传递正确的参数!");
            }

            if (IsChildAccount(currentUserInfo.RoleID))
            {
                drugViews = drugViews.Where(d => d.CityID == Params.CityID && d.AreaID == currentUserInfo.CurrentAreaID);
            }
            else if (Params.AreaID > 0)
            {
                drugViews = drugViews.Where(d => d.CityID == Params.CityID && Params.AreaID == d.AreaID);
            }
            else
            {
                drugViews = drugViews.Where(d => d.CityID == Params.CityID);
            }
            #endregion
            var d1 = drugViews.ToArray();
            drugViews = await QueryPipeLineTime(pipeLineParameter, drugViews);
            var d2 = drugViews.ToArray();
            var data = drugDetailRepository.GroupByDrugDetailPlaceAverage(drugViews);

            return Ok200("查询成功!", await PageList<DrugDetailEntity>.CreateAsync(data, Params));

        }


        /// <summary>
        /// 统计各个区域的毒品的折算总量根据时间历史值得话就不用传时间
        /// </summary>
        /// <returns></returns>
        public async Task<BaseMessage> GetHistoryTop(TopParameter Params, CurrentUserInfo currentUserInfo)
        {
            var drugDetaionViews = drugDetailRepository.GetDrugDetails(d => true);


            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
                Year = Params.Year,
            };

            drugDetaionViews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugDetaionViews);

            drugDetaionViews = await QueryPipeLineTime(pipeLineParameter, drugDetaionViews);

            List<HistoryTopView> historys = new List<HistoryTopView>();
            if (await drugDetaionViews.AnyAsync())
            {
                var data = await drugDetaionViews.GroupBy(d => new { d.MonitoringSite, d.MonitorTime }).Select(d => new
                {
                    MonitoringSite = d.Key.MonitoringSite,
                    ReducedTotal = d.Max(t => t.ReducedTotal),
                    MonitorTime = d.Key.MonitorTime

                }).ToListAsync();


                for (int i = 0; i < data.Count; i++)
                {
                    if (i > 0 && historys[historys.Count - 1].name == data[i].MonitoringSite)
                    {
                        if (historys[historys.Count - 1].value <= data[i].ReducedTotal)
                        {
                            historys[historys.Count - 1].value = data[i].ReducedTotal;
                            historys[historys.Count - 1].date = data[i].MonitorTime;
                        }
                    }
                    else
                    {
                        HistoryTopView top = new HistoryTopView();
                        top.name = data[i].MonitoringSite;
                        top.value = data[i].ReducedTotal;
                        top.date = data[i].MonitorTime;
                        historys.Add(top);
                    }
                }
            }
            return Ok200("查询成功!", historys);
        }

        public async Task<BaseMessage> GetRankTotal(PieParameter Params, CurrentUserInfo currentUserInfo)
        {



            #region data 
            var drugDetaionViews = drugDetailRepository.GetDrugDetails(d => d.MonitorTime.Year == Params.Year);

            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
            };

            drugDetaionViews = QueryPipeLineRoleNoCity(pipeLineParameter, currentUserInfo, drugDetaionViews);

            drugDetaionViews = await QueryPipeLineTime(pipeLineParameter, drugDetaionViews);
            #endregion

            #region 映射成键值对

            List<HistoryTopView> historys = new List<HistoryTopView>();
            if (await drugDetaionViews.AnyAsync())
            {
                var data = await drugDetailRepository.GroupByDrugDetailPlaceAverageAsync(drugDetaionViews);

                foreach (var dic in data)
                {

                    HistoryTopView top = new HistoryTopView();
                    top.name = dic.MonitoringSite;
                    top.value = Math.Round(dic.ReducedTotal, 2);
                    top.date = dic.MonitorTime;
                    historys.Add(top);
                }
            }

            #endregion
            return Ok200("查询成功!", historys);
        }
        /// <summary>
        /// 消耗排行
        /// </summary>
        /// <returns></returns>
        public async Task<BaseMessage> GetRank(PieParameter Params, CurrentUserInfo currentUserInfo)
        {
            #region query
            List<DrugRankView> ranks = new List<DrugRankView>();
            #endregion
            var drugDetaionViews = drugDetailRepository.GetDrugDetails(d => d.MonitorTime.Year == Params.Year);
            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
            };
            drugDetaionViews = QueryPipeLineRoleNoCity(pipeLineParameter, currentUserInfo, drugDetaionViews);
            drugDetaionViews = await QueryPipeLineTime(pipeLineParameter, drugDetaionViews);
            #region MappingKeyValue

            if (await drugDetaionViews.AnyAsync())
            {
                var drugdetaildata = await drugDetailRepository.GroupByDrugDetailPlaceAverageAsync(drugDetaionViews);
                Type type = typeof(DrugDetailEntity);

                foreach (PropertyInfo prop in type.GetProperties())
                {
                    string Name = prop.GetColName();
                    if (prop.PropertyType == typeof(double) && Name.Contains("（"))
                    {
                        List<PieView> pie = new List<PieView>();
                        foreach (var drugDetail in drugdetaildata)
                        {
                            double.TryParse(prop.GetValue(drugDetail).ToString(), out double val);
                            pie.Add(new PieView()
                            {
                                Value = Math.Round(val, 2),
                                Name = drugDetail.MonitoringSite
                            });
                        }
                        ranks.Add(new DrugRankView()
                        {
                            Name = Name.Substring(0, Name.IndexOf("（")),
                            Pies = pie
                        });
                    }
                }
            }

            #endregion
            return Ok200("查询成功!", ranks);
        }

        public async Task<BaseMessage> GetSynthesize(SynthesizeParameter Params, CurrentUserInfo currentUserInfo)
        {
            double precent = Convert.ToDouble(Convert.ToInt32(configuration["PersionPrecent"]));



            int quarter = Params.Month.GetQuarter();
            int Pastquarter = quarter.GetPastQuarter();


            int PastYear = quarter.GetByPastQuarterYear(Params.Year);

            int PlusPastquarter = Pastquarter.GetPastQuarter();
            int PlusPastYear = Pastquarter.GetByPastQuarterYear(PastYear);

            var drugDetaionViews = drugDetailRepository.GetDrugDetails(d => !d.AreaName.Contains("无"));
            List<PieView> pies = new List<PieView>();

            PipeLineParameter pipeLineParameterCurrent = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
            };

            PipeLineParameter pipeLineParameterPast = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month - 1,
                Quarter = Pastquarter,
            };


            drugDetaionViews = QueryPipeLineRole(pipeLineParameterCurrent, currentUserInfo, drugDetaionViews, false);

            #region 同比值
            if ((await drugDetaionViews.AnyAsync()))
            {
                pies.Add(new PieView
                {
                    Name = "检测点数量",
                    Value = await drugDetaionViews.Where(t=>t.AreaID>0).GroupBy(t => t.MonitoringSite).CountAsync()
                });

                if (await (await QueryPipeLineTime(pipeLineParameterCurrent, drugDetaionViews.Where(t => t.MonitorTime.Year == PastYear))).AnyAsync())
                {
                    pies.Add(new PieView
                    {
                        Name = "同比值",
                        Value = (await (await QueryPipeLineTime(pipeLineParameterCurrent, drugDetaionViews.Where(t => t.MonitorTime.Year == PastYear)))
                        .GroupBy(d => new { }).
                         Select(t => new { SumTotal = t.Average(t => t.ReducedTotal) }).ToListAsync()).FirstOrDefault().SumTotal
                    });

                }
                else
                {
                    pies.Add(new PieView()
                    {
                        Name = "同比值-无数据",
                        Value = -999999
                    });
                }

            }
            #endregion



            #region 查询人数
            var placeDuty = from duty in placeDutyRepository._dbContext.PlaceDutys.AsNoTracking() select duty;
            #region 区域人口数
            if (Params.AreaID != -1)
            {
                placeDuty = placeDuty.Where(d => d.CityID == Params.CityID && d.AreaID == Params.AreaID);
            }
            else
            {
                placeDuty = placeDuty.Where(d => d.CityID == Params.CityID);
            }
            #endregion

            if (await placeDuty.AnyAsync())
            {
                double SumPeople = Math.Round(Convert.ToDouble((await placeDuty.GroupBy(p => new { }).Select(p => new
                {
                    SumPeople = p.Sum(t => t.NumPeople)
                }).ToListAsync()).FirstOrDefault().SumPeople / precent), 2);
                pies.Add(new PieView()
                {
                    Name = "人口数量",
                    Value = SumPeople
                });
            }
            else
            {
                pies.Add(new PieView()
                {
                    Name = "人口数量-无",
                    Value = -999999
                });
            }

            #endregion

            #region 综合指标
            PieView pie = new PieView();
            int nowQuarter = -1;
            if (await (await QueryPipeLineTime(pipeLineParameterCurrent, drugDetaionViews)).AnyAsync())
            {

                pie.Name = "本期综合指标";
                pie.Value = (await (await QueryPipeLineTime(pipeLineParameterCurrent, drugDetaionViews)).
                       GroupBy(t => new { }).Select(
                           t => new { AvgTotal = t.Average(p => p.ReducedTotal) }).
                           ToListAsync()).FirstOrDefault().AvgTotal;
                nowQuarter = quarter;
            }
            else
            {
                {
                    pie.Name = "本季综合指标-无";
                    pie.Value = -999999;

                }

            }

            pies.Add(pie);
            pies.Add(new PieView() { Name = "quarter", Value = nowQuarter });
            #endregion

            #region 历史

            pies.Add(new PieView()
            {
                Name = "历史综合",
                Value = Math.Round((await drugDetaionViews.
          GroupBy(t => new { }).Select(
              t => new { AvgTotal = t.Average(p => p.ReducedTotal) }).
              ToListAsync()).FirstOrDefault().AvgTotal, 2)
            });
            #endregion

            #region 环比值
            PieView piepast = new PieView() { Name = "环比变化幅度" };
            if (await (await QueryPipeLineTime(pipeLineParameterPast, drugDetaionViews)).AnyAsync())
            {
                piepast.Value = (await (await QueryPipeLineTime(pipeLineParameterPast, drugDetaionViews)).
           GroupBy(t => new { }).Select(
               t => new { AvgTotal = t.Average(p => p.ReducedTotal) }).
               ToListAsync()).FirstOrDefault().AvgTotal;
                piepast.Value = Math.Round((pie.Value - piepast.Value) / piepast.Value * 100, 2);
            }
            else
            {

                piepast.Name = "环比变化幅度--无数据";
                piepast.Value = -999999;
            }

            pies.Add(piepast);
            #endregion

            return Ok200("查询成功!", pies);
        }

        public async Task<BaseMessage> GetChangeScpe(PieParameter Params, CurrentUserInfo currentUserInfo)
        {
            #region data
            var query = drugDetailRepository.GetDrugDetails(d => true);
            IQueryable<DrugDetailUnion> pastquarter = null;
            IQueryable<DrugDetailUnion> pastyear = null;


            Type type = typeof(DrugDetailEntity);

            int quarter = Params.Month.GetQuarter();


            int pastYear = quarter.GetByPastQuarterYear(Params.Year);
            int pastQuarter = quarter.GetPastQuarter();

            int PlusPastYear = Params.Year - 1;
            int PlusQuarter = pastQuarter.GetPastQuarter();
            #endregion

            PipeLineParameter pipeLineParameterCurrent = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
            };
            PipeLineParameter pipeLineParameterPast = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month.GetPastMonth(),
                Quarter = Params.Quarter.GetPastQuarter(),
            };

            query = QueryPipeLineRoleNoCity(pipeLineParameterCurrent, currentUserInfo, query);

            pastquarter = query;
            pastyear = query;

            pastquarter = await QueryPipeLineTime(pipeLineParameterPast, query.Where(d => d.MonitorTime.Year == pastYear));
            pastyear = await QueryPipeLineTime(pipeLineParameterCurrent, query.Where(d => d.MonitorTime.Year == PlusPastYear));
            query = await QueryPipeLineTime(pipeLineParameterCurrent, query.Where(d => d.MonitorTime.Year == Params.Year));



            bool IsPastQuerter = false;
            bool IsPastYear = false;
            bool IsNow = true;
            DrugDetailEntity data = new DrugDetailEntity();
            DrugDetailEntity pastQuarterDate = new DrugDetailEntity();
            DrugDetailEntity pastyearDate = new DrugDetailEntity();
            List<ChangeScpeView> csv = new List<ChangeScpeView>();

            IsPastQuerter = await pastquarter.AnyAsync();
            IsPastYear = await pastyear.AnyAsync();
            IsNow = await query.AnyAsync();
            if (IsNow)
            {
                data = await drugDetailRepository.GroupByAverage(query);
            }
            #region 本季度值

            #endregion

            #region 上季度同期值
            if (IsPastQuerter)
            {
                pastQuarterDate = await drugDetailRepository.GroupByAverage(pastquarter);
                #endregion
            }
            #region 去年同期值
            if (IsPastYear)
            {
                pastyearDate = await drugDetailRepository.GroupByAverage(pastyear);
                #endregion
            }
            foreach (var item in type.GetProperties())
            {
                ChangeScpeView cv = new ChangeScpeView();
                string name = item.GetColName();
                if (name.Contains("（") && item.PropertyType == typeof(double))
                {
                    cv.Name = name.Substring(0, name.IndexOf("（"));
                    if (IsNow)
                    {
                        cv.NowValue = Math.Round((double)item.GetValue(data), 2);
                    }
                    if (IsPastQuerter)
                    {
                        double.TryParse(item.GetValue(pastQuarterDate).ToString(), out double res);
                        cv.PastValue = cv.NowValue.GetPercent(res);
                    }

                    if (IsPastYear)
                    {

                        double.TryParse(item.GetValue(pastyearDate).ToString(), out double res);
                        cv.PastYearValue = cv.NowValue.GetPercent(res);
                    }

                    csv.Add(cv);
                }
            }

            return Ok200("查询成功!", csv);
        }
        public async Task<bool> GetTest()
        {
            #region 超过预警值发送警报

            var confgAram = from alarm in setAlarmRepository._dbContext.SetAlarm.AsNoTracking()
                            join moreyellow in detailRepository._dbContext.Details.AsNoTracking() on alarm.MoreYellowID equals moreyellow.ID
                            join morered in detailRepository._dbContext.Details.AsNoTracking() on alarm.MoreRedID equals morered.ID
                            join moreonceyellow in detailRepository._dbContext.Details.AsNoTracking() on alarm.MoreOnceYellowID equals moreonceyellow.ID
                            join moreoncered in detailRepository._dbContext.Details.AsNoTracking() on alarm.MoreOneceRedID equals moreoncered.ID
                            select new
                            {
                                MoreYellowValue = moreyellow.RowDesc,
                                MoreRedValue = morered.RowDesc,
                                MoreOnceRedValue = moreonceyellow.RowDesc,
                                MoreOnceYellowValue = moreoncered.RowDesc,
                                StandardValue = alarm.StandardValue,

                            };
            var confgAramData = await confgAram.FirstOrDefaultAsync();

            var presentQuery = from drug in drugDetailRepository._dbContext.DrugDetail.AsNoTracking().Where(d => d.MonitorTime.Month >= DateTime.Now.Month - 1)
                               join alarm in alarmPlaceRepository._dbContext.AlaramPlace.AsNoTracking() on drug.AreaID equals alarm.AreaID
                               select new
                               {
                                   AreaID = drug.AreaID,
                                   MonitorTime = drug.MonitorTime,
                                   ReducedTotal = drug.ReducedTotal,
                                   PresentMonth = alarm.PresentMonth,
                                   RoseCount = alarm.RoseCount
                               };
            var AlarmKeyValue = alarmPlaceRepository._dbContext.AlaramPlace.AsNoTracking().ToDictionary(t => t.AreaID.ToString(), t => new AlaramPlaceEntity()
            { ID = t.ID, PresentMonth = t.PresentMonth, RoseCount = t.RoseCount, AreaID = t.AreaID });

            var presentDate = await presentQuery.GroupBy(t => new { t.AreaID, t.MonitorTime.Month }).Select(d => new
            {
                Avg = d.Average(t => t.ReducedTotal),
                AreaID = d.Key.AreaID,
                Month = d.Key.Month,


            }).ToListAsync();

            for (int i = 0; i < presentDate.Count; i++)
            {
                if (presentDate[i].AreaID == presentDate[i + 1].AreaID)
                {
                    double upValue = (presentDate[i + 1].Avg - presentDate[i].Avg) / presentDate[i].Avg;
                    if (upValue > double.Parse(confgAramData.MoreYellowValue))
                    {
                        if (upValue > double.Parse(confgAramData.MoreRedValue))
                        {
                            //发红色
                        }
                        else
                        {
                            //发黄色警告
                        }
                    }
                    else
                    {
                        if (upValue > 0)
                        {
                            //记录上涨次数
                            AlaramPlaceEntity item = AlarmKeyValue[presentDate[i].AreaID.ToString()];
                            item.PresentMonth = 1;
                            if (item.RoseCount + item.PresentMonth >= double.Parse(confgAramData.MoreOnceYellowValue))
                            {
                                if (item.RoseCount + item.PresentMonth >= double.Parse(confgAramData.MoreRedValue))
                                {
                                    //上涨次数红色警报
                                }
                                else
                                {
                                    //上涨次数黄色警报
                                }
                            }
                        }
                    }
                }
                i++;
            }
            #endregion
            return true;
        }

        public async Task<BaseMessage> GetYears(int CompanyID)
        {
            var query = from drug in drugDetailRepository.Where(t => t.CompanyID == CompanyID) select drug;
            if (await query.AnyAsync() == false)
            {
                return BadRequest400("无数据请先导入数据!");
            }
            var pies = await drugDetailRepository.GetTimeGroupByQuarterOrMonth(query, (int)eGroupGetDateType.Year);
            foreach (var pie in pies)
            {
                pie.Name = $"{pie.Value} 年";
            }

            return Ok200("查询成功!", pies);
        }

        /// <summary>
        /// 获取季度 打印报告的时候
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="CompanyID"></param>
        /// <param name="monthOrQuarter"></param>
        /// <returns></returns>
        public async Task<BaseMessage> GetReportTerm(int Year, int CompanyID, int monthOrQuarter = -1)
        {

            IQueryable<DrugDetailEntity> query = from drug in drugDetailRepository.Where(t => t.CompanyID == CompanyID && t.MonitorTime.Year == Year) select drug;
            string strDescTime = string.Empty;
            if (_systemConfig.QuarterOrMonth == (int)eGroupGetDateType.Quarter)
            {
                query = query.Where(t => t.Quarter != monthOrQuarter);
                strDescTime = "季度";
            }
            else if (_systemConfig.QuarterOrMonth == (int)eGroupGetDateType.Month)
            {
                query = query.Where(t => t.MonitorTime.Month != monthOrQuarter);
                strDescTime = "月份";
            }

            List<PieView> pies = new List<PieView>();
            if (await query.AnyAsync())
            {
                pies = await drugDetailRepository.GetTimeGroupByQuarterOrMonth(query, _systemConfig.QuarterOrMonth);

                foreach (var pie in pies)
                {
                    pie.Name = $"第{pie.Value}{strDescTime}";
                }
            }
            return Ok200("数据获取成功!", pies);
        }

        public async Task<DataMessage> GetReport(ReportParameter Params)
        {

            var CurrentPieView = systemEnvService.GetSystemEnv().GetData<PieView>();
            int[] a = new int[10];
            PipeLineMoreParameter pipeLineMorePastParams = new PipeLineMoreParameter();

            if (Params.Compares != null && Params.Compares.Count > 0)
            {
                pipeLineMorePastParams.Months = Params.Compares.Select(c => c.Month).ToArray();
                pipeLineMorePastParams.Years = Params.Compares.Select(c => c.Year).ToArray();
                pipeLineMorePastParams.Quarters = Params.Compares.Select(c => c.Quarter).ToArray();
            }

            else
            {

                if (_systemConfig.QuarterOrMonth == (int)eGroupGetDateType.Month)
                {
                    pipeLineMorePastParams.Years = new int[1] { Params.Month.GetPastYearByMonth(Params.Year) };
                    pipeLineMorePastParams.Months = new int[1] { Params.Month.GetPastMonth() };
                }
                else if (_systemConfig.QuarterOrMonth == (int)eGroupGetDateType.Quarter)
                {
                    pipeLineMorePastParams.Years = new int[1] { Params.Quarter.GetByPastQuarterYear(Params.Year) };
                    pipeLineMorePastParams.Quarters = new int[1] { Params.Quarter.GetPastQuarter() };
                }

            }


            string ImgPath = configuration["ImgPath"];


            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Params.CompanyID.ToString(),
                Params.CityID.ToString(), Params.Quarter.ToString());

            string name = $"{Params.CompanyID}_{Params.CityID}_{Params.Quarter}";
            string filePath = Path.Combine(path, $"{Params.CompanyID}_{Params.CityID}_{Params.Quarter}.docx");
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            if (Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);
            }

            #region 取出值 各个地区毒品值
            IQueryable<DrugDetailUnion> drugData=null;
            PipeLineParameter pipeLineParams = new PipeLineParameter()
            {
                CityID = Params.CityID,
                Year = Params.Year,
                Month = Params.Month,
                Quarter = Params.Quarter,
            };
            IQueryable<DrugDayView> QuerydrugDay = null;
            IQueryable<DrugDetailUnion> drugDataPast =null;
            IQueryable<DrugUnion> query = null;
            ///支持区的报告导出
            if (Params.AreaID > 0)
            {
                drugData = drugDetailRepository.GetDrugDetails(drug => drug.CityID == Params.CityID && drug.CompanyID == Params.CompanyID && drug.MonitorTime.Year == Params.Year && (Params.AreaID.Equals(drug.AreaID) || drug.AreaID.Equals(-1)));
                QuerydrugDay=drugDayRepository.GetDrugViews(drug => drug.CityID == Params.CityID && Params.CompanyID == drug.CompanyID && drug.MonitorTime.Year == Params.Year && (Params.AreaID.Equals(drug.AreaID)|| drug.AreaID.Equals(-1)));
                drugDataPast = drugDetailRepository.GetDrugDetails(drug => drug.CityID == Params.CityID && Params.CompanyID == drug.CompanyID &&( Params.AreaID.Equals(drug.AreaID) || drug.AreaID.Equals(-1)));
                query = drugRepository.GetDrugDto(drug => drug.MonitorTime.Year == Params.Year && drug.CompanyID == Params.CompanyID && drug.CityID == Params.CityID && (Params.AreaID.Equals(drug.AreaID) || drug.AreaID.Equals(-1)));
            }
            else
            {
                drugData = drugDetailRepository.GetDrugDetails(drug => drug.CityID == Params.CityID && drug.CompanyID == Params.CompanyID && drug.MonitorTime.Year == Params.Year);
                QuerydrugDay=drugDayRepository.GetDrugViews(drug => drug.CityID == Params.CityID && Params.CompanyID == drug.CompanyID && drug.MonitorTime.Year == Params.Year);
                drugDataPast = drugDetailRepository.GetDrugDetails(drug => drug.CityID == Params.CityID && Params.CompanyID == drug.CompanyID);
                query = drugRepository.GetDrugDto(drug => drug.MonitorTime.Year == Params.Year && drug.CompanyID == Params.CompanyID && drug.CityID == Params.CityID);
            }

            drugData = await QueryPipeLineTime(pipeLineParams, drugData);
            QuerydrugDay = await QueryPipeLineTime(pipeLineParams, QuerydrugDay);
            drugDataPast = QueryPipeLineTime(pipeLineMorePastParams, drugDataPast);
            query = await QueryPipeLineTime(pipeLineParams, query);

            var data = drugData.ToList();
            if (await drugData.AnyAsync())
            {
                List<DrugDayView> GroupDrugDayData = new List<DrugDayView>();


                if (await QuerydrugDay.AnyAsync())
                {

                    GroupDrugDayData = await drugDayRepository.GroupByDrugDays(QuerydrugDay);
                }
                var GroupDrugData = await drugDetailRepository.GroupDrugDetails(drugData);



                List<DrugDetailReprot> GroupDrugDataPast = null;

                List<DrugDetailReprot> AreaDataPast = null ;
                DrugDetailReprot CityData = null;
                List<DrugDetailReprot> CityDataPast = null;
                if (drugDataPast.Any() == false)
                {
                    //return BadRequest400($"{pipeLineMorePastParams.Years[0]}年 第{pipeLineMorePastParams.Quarters[0]} 季度无数据!", "");
                }
                else
                {
                    GroupDrugDataPast = await drugDetailRepository.GroupDrugDetails(drugDataPast);
                     AreaDataPast = GroupDrugDataPast.Where(t => t.AreaID != -1).ToList();
                     CityDataPast = GroupDrugDataPast.Where(t => t.AreaID == -1).ToList();
                }

                var QueryGroup = await drugRepository.GroupDrug(query);

                var AreaData = GroupDrugData.Where(t => t.AreaID != -1).ToList();
                CityData = GroupDrugData.Where(t => t.AreaID == -1).FirstOrDefault();
               
                if (CityDataPast!=null && CityDataPast.Any())
                {
                    foreach (var cityPast in CityDataPast)
                    {
                        cityPast.AreaDatas = AreaDataPast?.Where(area => area.Quarter == cityPast.Quarter && area.Year == cityPast.Year).ToList();
                    }
                }
                var AreaDrug = QueryGroup.Where(t => t.AreaID != -1).ToList();
                var CityDrug = QueryGroup.Where(t => t.AreaID == -1).FirstOrDefault();

                var areaDrugDay = GroupDrugDayData.Where(t => t.AreaID != -1).ToList();
                var cityDarugDay = GroupDrugDayData.Where(t => t.AreaID == -1).FirstOrDefault();
                sockerHelper.Send(new DataModel() { Type = 1, CompanyID = Params.CompanyID, Data = GroupDrugData });
                await Task.Delay(500 * 1);
                var socketData = new List<DrugDetailReprot>();
                socketData.AddRange(AreaData);
                if (AreaDataPast!= null)
                {
                    socketData.AddRange(AreaDataPast);
                }

                sockerHelper.Send(new DataModel() { Type = 2, CompanyID = Params.CompanyID, Data = socketData, Description = CurrentPieView.Name, QuarterOrMonth = Params.Quarter });
                await Task.Delay(500 * 1);
                sockerHelper.Send(new DataModel() { Type = 3, CompanyID = Params.CompanyID, Data = AreaDrug });
                await Task.Delay(500 * 1);
                sockerHelper.Send(new DataModel() { Type = 4, CompanyID = Params.CompanyID, Data = areaDrugDay });
                await Task.Delay(500 * 1);

                sockerHelper.Close();
                #endregion
                WordTemplate.CityName = CityData.CityName;
                #region  第一章
                await builderWordReportRepository.FirstSection(Params.Year, Params.Quarter, AreaData);

                #endregion

                #region 第二章


                await builderWordReportRepository.SecondSection();

                #endregion

                #region 第三章
                await builderWordReportRepository.ThirdSection(AreaData, CityData.ReducedTotal);
                #endregion

                #region 第四章
                await builderWordReportRepository.FourthSection(GroupDrugData, CityData, AreaData, CityDataPast);
                #endregion
                #region 第五章

                await builderWordReportRepository.FivethSection(CityData, GroupDrugData, Params.Quarter, Params.CompanyID, AreaData);


                #endregion

                #region 第六章

                await builderWordReportRepository.SixthSection(CityDrug, AreaDrug, CityData);

                #endregion

                #region 第七章
                await builderWordReportRepository.SevenSection(cityDarugDay, areaDrugDay, GroupDrugDayData);


                #endregion

                #region 末尾部分


                await builderWordReportRepository.EndSection(path, name, CityData, query.ToList());
                #endregion
            }



            return Ok200("生成成功!", filePath);
        }

        public async Task<BaseMessage> GetAreas(int cityID, int companyID, int currentArea, int roleId)
        {
            IQueryable<MonitoringSiteView> query = null;
            if (IsChildAccount(roleId))
            {
                query = drugRepository.GetMonitoringSites(t => t.company.CityID == cityID && t.company.ID == companyID && t.area.ID == currentArea);
            }
            else
            {
                if (await companyRepository.AnyAsync(t => t.ID == companyID))
                {
                    var companyView = await companyRepository.GetCompanies(t => t.ID == companyID).FirstOrDefaultAsync();
                    if (companyView.PlaceTypeName == "市")
                    {
                        query = drugRepository.GetMonitoringSites(t => t.company.CityID == cityID && t.company.ID == companyID);
                    }
                    else
                    {
                        query = drugRepository.GetMonitoringSites(t => t.company.CityID == cityID && t.company.ID == companyID && t.area.ID == companyView.AreaID);
                    }
                }
            }
            List<MonitoringSiteView> data = null;
            if (await query.AnyAsync())
            {
                data = await query.GroupBy(t => new { t.AreaID, t.AreaName, t.MonitoringSite }).Select(t =>
                new MonitoringSiteView()
                {
                    MonitoringSite = t.Key.MonitoringSite,
                    AreaName = t.Key.AreaName,
                    AreaID = t.Key.AreaID,
                    Latitude = t.Average(t => t.Latitude),
                    Longitude = t.Average(t => t.Longitude),
                }).ToListAsync();

                foreach (var item in data)
                {
                    string dic = Path.Combine(configuration["SewageFactoryImagePath"], companyID.ToString(), cityID.ToString(), item.AreaID.ToString());
                    if (Directory.Exists(dic))
                    {
                        foreach (var file in Directory.GetFiles(dic))
                        {
                            item.ImgUrls.Add($"{companyID}/{cityID}/{item.AreaID}/{file.GetFileName()}");
                        }
                    }
                }
            }

            return Ok200("查询成功!", data);
        }


        public async Task<BaseMessage> GetDrugDays(DrugDayParameter Params, CurrentUserInfo currentUserInfo)
        {
            var drugviews = drugDayRepository.GetDrugViews(drug => drug.MonitorTime.Year == Params.Year);
            PipeLineParameter pipeLineParameter = new PipeLineParameter()
            {
                AreaID = Params.AreaID,
                CompanyID = Params.CompanyID,
                CityID = Params.CityID,
                Month = Params.Month,
                Quarter = Params.Quarter,
            };
            drugviews = await QueryPipeLineTime(pipeLineParameter, drugviews);

            drugviews = QueryPipeLineRole(pipeLineParameter, currentUserInfo, drugviews);

            drugviews = drugDayRepository.GroupBySite(drugviews);
            return Ok200("查询成功!", await PageList<DrugDayView>.CreateAsync(drugviews, Params));
        }

        public async Task<BaseMessage> GetDate(DateParameter Params)
        {
            DateView dv = new DateView();
            DateTime date = DateTime.Parse("0001-01-01 00:00:00.000000");
            var drugquery = drugDetailRepository.GetDrugDetails(d => d.CompanyID == Params.CompanyID && d.CityID == Params.CityID && d.MonitorTime > date);
            if (Params.AreaID > 0)
            {
                drugquery = drugquery.Where(d => d.AreaID == d.AreaID);
            }
            if (await drugquery.AnyAsync())
            {
                DateDto Dto = await drugDetailRepository.GroupByDate(drugquery);
                dv.Month = Dto.Month;
                dv.Year = Dto.Year;
                dv.Quarter = Dto.Quarter;
                dv.description = $"{ dv.Year}年{dv.Quarter}季度{dv.Month}月";
            }
            return Ok200("查询成功!", dv);
        }
    }
}
